import Block from './block.js';
let levelData1 = null;

async function loadLevelData() {
  try {
    const response = await fetch('./levels.json');
    const data = await response.json();
    levelData1 = data;
  } catch (error) {
    return console.error('Error loading level data:', error);
  }
}



const GRID_SIZE = 100;
let currentLevel = 0;
let moveCount = 0;
let board = [];
let blocks = [];
const canvas = document.getElementById('game-board');

// 初始化游戏和渲染将在JSON数据加载完成后执行
// 初始化游戏
function initGame() {
  // 修改此处，使用导入的 levelData
  // if (!levelData1 || !levelData1[currentLevel] || !levelData1[currentLevel].boardSize || !levelData1[currentLevel].blocks || !levelData1[currentLevel].exit) {
  //   console.error('Invalid level data');
  //   return;
  // }
  // 验证所有方块的位置是否在棋盘范围内
const levelData = levelData1[currentLevel];
  const [rows, cols] = levelData.boardSize;
  for (const block of levelData.blocks) {
    if (block.x < 0 || block.y < 0 || 
        block.x + block.width > cols || 
        block.y + block.height > rows) {
      console.error('Block position out of bounds:', block);
      return;
    }
  }
  
  
  // 初始化棋盘
  board = Array.from({length: rows}, () => Array(cols).fill(0));
  // 创建方块实例
  blocks = levelData.blocks.map((b, i) => {
    for (let x = 0; x < b.width; x++) {
      for (let y = 0; y < b.height; y++) {
        board[b.y + y][b.x + x] = i + 1;
      }
    }
    return new Block(i+1, b.type, b.width, b.height, b.x, b.y);
  });
  renderBoard();

}


// 渲染棋盘
function renderBoard() {
  // const canvas = document.getElementById('game-board');
  const ctx = canvas.getContext('2d');
  
  // 绘制棋盘背景
  ctx.fillStyle = '#f0d9b5';
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // 绘制网格线
  ctx.strokeStyle = '#000';
  ctx.lineWidth = 2;
  for(let i = 0; i <= canvas.width/GRID_SIZE; i++) {
    ctx.beginPath();
    ctx.moveTo(i*GRID_SIZE, 0);
    ctx.lineTo(i*GRID_SIZE, canvas.height);
    ctx.stroke();
  }
  for(let j = 0; j <= canvas.height/GRID_SIZE; j++) {
    ctx.beginPath();
    ctx.moveTo(0, j*GRID_SIZE);
    ctx.lineTo(canvas.width, j*GRID_SIZE);
    ctx.stroke();
  }

  // 绘制方块
  blocks.forEach(block => {
    ctx.fillStyle = getBlockColor(block.type);
    ctx.fillRect(
      block.x * GRID_SIZE + 2,
      block.y * GRID_SIZE + 2,
      block.width * GRID_SIZE - 4,
      block.height * GRID_SIZE - 4
    );
    
    // 绘制文字标签
    ctx.fillStyle = '#fff';
    ctx.font = '20px Arial';
    ctx.textAlign = 'center';
    ctx.fillText(
      block.type,
      block.x * GRID_SIZE + block.width*GRID_SIZE/2,
      block.y * GRID_SIZE + block.height*GRID_SIZE/2 + 8
    );
  });
}

// 处理拖拽交互
let draggedBlock = null;
let dragStartX = 0;
let dragStartY = 0;

canvas.addEventListener('mousedown', (e) => {
  const rect = canvas.getBoundingClientRect();
  const x = Math.floor((e.clientX - rect.left) / GRID_SIZE);
  const y = Math.floor((e.clientY - rect.top) / GRID_SIZE);
  
  draggedBlock = blocks.find(b => 
    x >= b.x && x < b.x + b.width &&
    y >= b.y && y < b.y + b.height
  );
  
  if (draggedBlock) {
    dragStartX = e.clientX;
    dragStartY = e.clientY;
  }
});

canvas.addEventListener('mousemove', (e) => {
  if (!draggedBlock) return;
  
  const dx = e.clientX - dragStartX;
  const dy = e.clientY - dragStartY;
  const threshold = GRID_SIZE / 2;
  
  if (Math.abs(dx) > threshold || Math.abs(dy) > threshold) {
    const direction = 
      Math.abs(dx) > Math.abs(dy) ? 
        (dx > 0 ? 'right' : 'left') :
        (dy > 0 ? 'down' : 'up');
    
    if (Block.canMove(board, draggedBlock, direction, board[0].length, board.length)) {
      updateBoard(draggedBlock, direction);
      moveCount++;
      document.getElementById('move-count').textContent = `步数：${moveCount}`;
      renderBoard();
      
      if (checkWin()) {
        showNextLevelButton();
      }
    }
    
    draggedBlock = null;
  }
});

function updateBoard(block, direction) {
  // 清除原位置
  for (let y = block.y; y < block.y + block.height; y++) {
    for (let x = block.x; x < block.x + block.width; x++) {
      board[y][x] = 0;
    }
  }
  
  // 更新坐标
  if (direction === 'left') block.x--;
  else if (direction === 'right') block.x++;
  else if (direction === 'up') block.y--;
  else if (direction === 'down') block.y++;
  
  // 标记新位置
  for (let y = block.y; y < block.y + block.height; y++) {
    for (let x = block.x; x < block.x + block.width; x++) {
      board[y][x] = block.id;
    }
  }
}

// 精确胜利检测
function checkWin() {
  const caoBlock = blocks.find(b => b.type === '曹操');
  const exitPos = levelData1[currentLevel].exit;
  
  return (
    caoBlock.x <= exitPos[0] && 
    caoBlock.x + caoBlock.width >= exitPos[0] + 1 &&
    caoBlock.y <= exitPos[1] &&
    caoBlock.y + caoBlock.height >= exitPos[1] + 1
  );
}
// function start() {
//     initGame();
//     renderBoard();
// }
//事件监听
document.getElementById('start-game').addEventListener('click', () => {
  loadLevelData().then(() => {
    initGame();
    renderBoard();
    console.log('开始游戏');
  });
});
document.getElementById('reset-level').addEventListener('click', () => {
    moveCount = 0;
    document.getElementById('move-count').textContent = '步数：0';
    initGame();
});
function showNextLevelButton() {
  const btn = document.createElement('button');
  btn.id = 'next-level';
  btn.textContent = '下一关';
  btn.style.position = 'absolute';
  btn.style.left = '50%';
  btn.style.top = '50%';
  btn.style.transform = 'translate(-50%, -50%)';
  btn.style.padding = '10px 20px';
  btn.style.fontSize = '20px';
  btn.style.backgroundColor = '#007BFF';
  btn.style.color = '#fff';
  btn.style.border = 'none';
  btn.style.borderRadius = '5px';
  btn.style.cursor = 'pointer';
  document.getElementById('game-container').appendChild(btn);

  btn.addEventListener('click', () => {
    currentLevel = (currentLevel + 1) % levelData1.length;
    moveCount = 0;
    document.getElementById('move-count').textContent = '步数：0';
    btn.remove();
    initGame();
  });
}

function getBlockColor(type) {
  const colors = {
    '曹操': '#e74c3c',
    '关羽': '#2ecc71',
    '张飞': '#3498db',
    '士兵': '#95a5a6'
  };
  return colors[type] || '#34495e';
}